package com.zenglx.multilanguage.method;


import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.zenglx.multilanguage.metadata.ZlxTableInfo;
import com.zenglx.multilanguage.util.SqlHelper;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

/**
 * SelectList 兼容MP原生方法
 */
public class SelectById extends com.baomidou.mybatisplus.core.injector.methods.SelectById {

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        ZlxTableInfo zlxTableInfo = (ZlxTableInfo)tableInfo;
        if(zlxTableInfo.isMultiLanguage()) {
            SqlMethod sqlMethod = SqlMethod.SELECT_BY_ID;
            String scriptSql = "<script>SELECT %s FROM %s WHERE %s \n</script>";
            String sql = String.format(scriptSql, SqlHelper.getAllColumns(tableInfo), SqlHelper.selectFromTableTl(tableInfo),
                    sqlWhereEntityWrapper(true, tableInfo));
            SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
            return this.addSelectMappedStatementForTable(mapperClass, getMethod(sqlMethod), sqlSource, tableInfo);
        } else {
           return super.injectMappedStatement(mapperClass, modelClass, tableInfo);
        }
    }

    @Override
    protected String sqlWhereEntityWrapper(boolean newLine, TableInfo tableInfo) {
        ZlxTableInfo zlxTableInfo = (ZlxTableInfo)tableInfo;
        if(zlxTableInfo.isMultiLanguage()) {
            StringBuilder sb = new StringBuilder();
            sb.append("b.").append(zlxTableInfo.getKeyColumn())
                    .append("=#{id}");
            return sb.toString();
        } else {
            return super.sqlWhereEntityWrapper(newLine, tableInfo);
        }

    }
}
